package com.theeviljames.coursework.receiver;

import java.util.Hashtable;


public class ReceiverProtocol {

	private static ReceiverProtocol _instance = new ReceiverProtocol();
	private Hashtable<Integer, String> messages = new Hashtable<Integer, String>();
	private Hashtable<Integer, String> retransmitCodes = new Hashtable<Integer, String>();
	private Hashtable<Integer, String> retransmitStrings = new Hashtable<Integer, String>();
	
	private ReceiverProtocol(){
		init();
	}
	
	public static ReceiverProtocol getInstance(){
		return _instance;
	}
	
	public String getMessage(int number){
		return messages.get(number);
	}
	
	public String decodeRetransmit(int number){
		return retransmitCodes.get(number%10);
	}
	
	public String encodeRetransmit(int number){
		return messages.get(304)+number+"#"+retransmitStrings.get(number%10);
	}
	
	public int parseMessageString(String message){
		try{
			String s = message.substring(0, 3);
			int n = Integer.parseInt(s);
			if(messages.get(n)==null){
				return -1;
			}
			else return n;
		}
		catch(NumberFormatException e){
			return -1;
		}
	}
	
	
	private void init(){
		messages.put(101, "101 CONNECT?");
		messages.put(102, "102 CONNECT ACCEPT");
		messages.put(103, "103 CONNECTED");
		messages.put(104, "104 DELAY TEST");
		messages.put(105, "105 DELAY TEST COMPLETE");
		//Start Transmit
		messages.put(201, "201 START TRANSMIT");
		messages.put(202, "202 TRANSMIT ACCEPT DELAY=");
		//Transmissio
		messages.put(301, "301 SAMPLE #");
		messages.put(302, "302 BLEEP #");
		messages.put(303, "303 RETRANSMIT #");
		messages.put(304, "304 RETRANSMIT #");
		//Stop transmit
		messages.put(401, "401 STOP TRANSMIT");
		messages.put(402, "402 STOP TRANSMIT ACCEPT");
		//Disconnect
		messages.put(501, "501 DISCONNECT");
		messages.put(502, "502 DISCONNECT ACCEPT");

		messages.put(601, "601 UNKNOWN REQUEST");
		
		retransmitCodes.put(0, "One");
		retransmitCodes.put(1, "Two Two");
		retransmitCodes.put(2, "Three Three Three");
		retransmitCodes.put(3, "Four Four Four Four");
		retransmitCodes.put(4, "Five Five Five Five Five");
		retransmitCodes.put(5, "Six Six Six Six Six Six");
		retransmitCodes.put(6, "Seven Seven Seven Seven Seven Seven Seven");
		retransmitCodes.put(7, "Eight Eight Eight Eight Eight Eight Eight Eight");
		retransmitCodes.put(8, "Nine Nine Nine Nine Nine Nine Nine Nine Nine");
		retransmitCodes.put(9, "Ten Ten Ten Ten Ten Ten Ten Ten Ten Ten");
		
		retransmitStrings.put(0, "1");
		retransmitStrings.put(1, "22");
		retransmitStrings.put(2, "333");
		retransmitStrings.put(3, "4444");
		retransmitStrings.put(4, "55555");
		retransmitStrings.put(5, "666666");
		retransmitStrings.put(6, "7777777");
		retransmitStrings.put(7, "88888888");
		retransmitStrings.put(8, "999999999");
		retransmitStrings.put(9, "10101010101010101010");
		
	}
}
